<?php
/**
 * 公共模型  Article
 * */
namespace app\common\model;
use think\Model;

class Article extends Model
{
    public function articleData(){
        $res = $this->select();
    }

    /**
     * 详情数据
     * */
    public function articleInfo($id){
        return $this->get($id);
    }
    
    /**
     * 分页数据
     * */
    public function articlePage($page, $listRows = null,$where='',$order='id desc'){
        $res = $this->where($where)->order($order)->page($page,$listRows)->select();

        // 格式化数据
        foreach ($res as $k=>$v){
            // 转数组
            $thumb_arr = $this->thumbArray($v['thumb']);
            $res[$k]['thumb_arr'] = $thumb_arr;
            // 取封面
            $thumb_top = $this->thumbTop($v['thumb']);
            $res[$k]['thumb_top'] = $thumb_top;
            // 标签
            $tag = $this->articleTag($v['tag']);
            $res[$k]['tag'] = $tag;

        }
        return $res;
    }

    /**
     * 更新点击数
     * */
    public function updateHit($id){
        $where['id'] = $id;
        // 延迟更新60s
        $res = $this->where($where)->setInc('hit',1,config('data_expire'));
        $res;
    }









    /**
     * 相册 转数组格式
     * */
    public function thumbArray($json){
        return json_decode($json,true);
    }

    /**
     * 取出封面
     * @param $thumb json 格式
     * @return string 返回地址图片
     * */
    public function thumbTop($json){
        $arr = $this->thumbArray($json);
        if(empty($arr)) return false;
        foreach($arr as $k=>$v){
            if($v['top'] = 1){
                $top = $v['src'];
            }
        }
        return $top;
    }

    /**
     * 标签名称
     * */
   public function tagDataName($id){
        $res = db('category')->find($id);
        if($res){
            $name = $res['name'];
        }else{
            $name = '';
        }
        return $name;
    }

    /**
     * 取出文章标签
     * */
    public function articleTag($str){
        $arr = explode(',',$str);

        foreach($arr as $k=>$v){
            $t[] = $this->tagDataName($v);
        }
        return implode(',',$t);
    }


}